﻿using _8Group.MES.ISongService.MdItemType;
using _8Group.MES.ISongService.MdItemType.DTO;
using FourGroups.Project;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Yitter.IdGenerator;
using static Volo.Abp.Identity.IdentityPermissions;

namespace _8Group.MES.SongService
{
    [ApiExplorerSettings(GroupName = "宋恒漳")]
    public class MdItemTypeService : ApplicationService, IMdItemTypeService
    {
        /// <summary>
        /// 仓储
        /// </summary>
        private readonly IRepository<MdItemType, int> _mdItemTypeRepository;

        /// <summary>
        /// 构造函数    
        /// </summary>
        /// <param name="mdItemTypeRepository">仓储</param>
        public MdItemTypeService(IRepository<MdItemType, int> mdItemTypeRepository)
        {
            _mdItemTypeRepository = mdItemTypeRepository;

        }

        /// <summary>
        /// 获取所有物料产品列表
        /// </summary>
        /// <param name="requestMd"></param>
        /// <returns></returns>
        public async Task<object> GetMdItemTypeListAsync(RequestMdItemTypeDTO requestMd)
        {
            try
            {
                var list = await _mdItemTypeRepository.GetQueryableAsync();
                var mdItemTypes = list.AsQueryable();

                // 条件过滤
                if (!string.IsNullOrEmpty(requestMd.name))
                {
                    mdItemTypes = mdItemTypes.Where(x => x.ItemTypeName.Contains(requestMd.name));
                }

                if (!string.IsNullOrEmpty(requestMd.type))
                {
                    if (char.TryParse(requestMd.type, out char enableFlag))
                    {
                        mdItemTypes = mdItemTypes.Where(x => x.EnableFlag == enableFlag);
                    }
                }

                // 实现分页
                int totalCount = mdItemTypes.Count();
                mdItemTypes = mdItemTypes.OrderBy(x => x.Id)
                                         .Skip(((requestMd.page - 1) ?? 0) * (requestMd.limit ?? 10))
                                         .Take(requestMd.limit ?? 10);

                var itemlist = mdItemTypes.ToList(); // 使用异步方式
                var result = itemlist.Select(item => new GetMdItemTypeDTO
                {
                    ParentTypeId = item.ParentTypeId,
                    ItemOrProduct = item.ItemOrProduct,
                    ItemTypeCode = item.ItemTypeCode,
                    OrderNum = item.OrderNum,
                    CreateBy = item.CreateBy,
                    CreateTime = item.CreateTime,
                    EnableFlag = item.EnableFlag,
                    Id = item.Id,
                    ItemTypeName = item.ItemTypeName,
                }).ToList();

                var tree = GetCascader(result);

                var results = new ResponseModel
                {
                    data = tree,
                    code = "0", // 适当设置成功代码
                    count = totalCount, // 加入总数量
                    msg = "获取成功"
                };
                return results; // 直接返回对象而不是 JSON 字符串
            }
            catch (Exception ex)
            {
                // 处理异常并记录日志
                return new ResponseModel
                {
                    data = null,
                    code = "500",
                    msg = $"发生错误: {ex.Message}"
                };
            }
        }


        /// <summary>
        /// 获取树形结构数据
        /// </summary>
        /// <param name="mdItemTypes"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        private List<GetMdItemTypeDTO> GetCascader(IEnumerable<GetMdItemTypeDTO> mdItemTypes, int? pid = null)
        {
            var list = mdItemTypes.ToLookup(x => x.ParentTypeId);//根据父级ID进行分组
            return list[pid ?? 0].Select(item => new GetMdItemTypeDTO
            {
                ParentTypeId = item.ParentTypeId,
                ItemOrProduct = item.ItemOrProduct,
                ItemTypeCode = item.ItemTypeCode,
                OrderNum = item.OrderNum,
                CreateBy = item.CreateBy,
                CreateTime = item.CreateTime,
                EnableFlag = item.EnableFlag,
                Id = item.Id,
                ItemTypeName = item.ItemTypeName,
                children = GetCascader(mdItemTypes, item.Id)
            }).ToList();
        }

        /// <summary>
        /// 新增 物料产品分类
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<int> AddMdItemTypeAsync(AddMdItemTypeDTO input)
        {
            try
            {
                //重名判断
                var mdItemType = await _mdItemTypeRepository.FirstOrDefaultAsync(x => x.ItemTypeName == input.ItemTypeName);
                if (mdItemType != null)
                {
                    return 0;
                }
                else
                {
                    input.CreateBy = "宋恒漳";
                    input.CreateTime = DateTime.Now;
                    input.ItemTypeCode = YitIdHelper.NextId().ToString();
                    input.Ancestors = "0";
                    //使用AutoMapperExt进行DTO到实体的映射
                    var mdItemTypes = AutoMapperExt.MapTo<MdItemType>(input);
                    await _mdItemTypeRepository.InsertAsync(mdItemTypes);
                    return 1;
                }

            }
            catch (Exception)
            {
                return 0;
            }
        }

        /// <summary>
        /// 更新 物料产品分类
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> UpdateMdItemTypeAsync(UpdMdItemTypeDTO input)
        {
            input.UpdateBy = "宋恒漳";
            input.UpdateTime = DateTime.Now;
            //使用AutoMapperExt进行DTO到实体的映射
            var mdItemType = AutoMapperExt.MapTo<MdItemType>(input);
            await _mdItemTypeRepository.UpdateAsync(mdItemType);
            return true;
        }

        /// <summary>
        /// 删除物料产品分类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteMdItemTypeAsync(int id)
        {
            var mdItemType = await _mdItemTypeRepository.GetAsync(id);
            await _mdItemTypeRepository.DeleteAsync(mdItemType, true);
            return true;
        }
    }
}
